import AntModal from "@/components/pt/dialog/AntModal";
import {
  getBizPushRule,
  addBizPushRule,
  updateBizPushRule,
  findMaxSort,
  findExistBizPushRule,
} from "@/api/biz/bizPushRule";

import { findUserJoinRuleList } from "@/api/biz/bizPushRuleUser";
import SelectUser from "@/components/pt/selectUser/SelectUser";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import DeptTree from "@/views/system/user/modules/DeptTree";

export default {
  name: "CreateForm",
  props: {
    ruleTypeOptions: {
      type: Array,
      required: true,
    },

    laiyuanOptions: {
      type: Array,
      required: true,
    },

    tagsOptions: {
      type: Array,
      required: true,
    },

    statusOptions: {
      type: Array,
      required: true,
    },
    cityOptions: {
      type: Array,
      required: true,
    },
    deptOptions: {
      type: Array,
      required: true,
    },
    expandedKeys: {
      type: Array,
      required: true,
    },
    ruleLogicOptions: {
      type: Array,
      required: true,
    },
  },
  components: {
    AntModal,
    SelectUser,
    AdvanceTable,
    DeptTree,
  },
  data() {
    return {
      open: false,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      total: 0,
      id: undefined,
      formTitle: "添加分配规则",
      // 表单参数
      form: { ruleUsers: [] },
      // deptOptions: [],
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
      },
      rules: {
        ruleName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        ruleType: [
          { required: true, message: "类型不能为空", trigger: "blur" },
        ],
        ruleLogic: [
          { required: true, message: "方式不能为空", trigger: "blur" },
        ],
        ruleCities: [
          { required: true, message: "城市不能为空", trigger: "blur" },
        ],
        laiyuan: [{ required: true, message: "线索不能为空", trigger: "blur" }],
      },
      columns: [
        {
          title: "姓名",
          dataIndex: "name",
          ellipsis: true,
          align: "center",
          width: "80px",
        },
        {
          title: "部门",
          dataIndex: "deptName",
          ellipsis: true,
          align: "center",
          width: "100px",
        },
        {
          title: "是否启用",
          dataIndex: "isEnable",
          ellipsis: true,
          align: "center",
          width: "80px",
          // fixed: "left",
          scopedSlots: { customRender: "isEnable" },
        },
        {
          title: "当日最大接单量",
          dataIndex: "maxCount",
          ellipsis: true,
          align: "center",
          width: "90px",
          // fixed: "left",
          scopedSlots: { customRender: "maxCount" },
        },
        {
          title: "当日已接单量",
          dataIndex: "sharedCount",
          ellipsis: true,
          align: "center",
          width: "90px",
          // fixed: "left",
        },
        // {
        //   title: "累计接单量",
        //   dataIndex: "totalCount",
        //   ellipsis: true,
        //   align: "center",
        //   width: "90px",
        //   // fixed: "left",
        // },
        // {
        //   title: "权重",
        //   dataIndex: "weight",
        //   ellipsis: true,
        //   align: "center",
        //   width: "90px",
        //   visible: false,
        //   // fixed: "left",
        //   // scopedSlots: { customRender: "weight" },
        // },
      ],
    };
  },
  filters: {},

  computed: {},
  watch: {},
  mounted() {},
  methods: {
    clickDeptNode(node) {
      this.queryParam.deptId = node.$options.propsData.eventKey;

      this.getList();
    },

    setDataOptionInfo(treeDataOption) {
      this.deptOptions = treeDataOption;
    },

    /** 新增和修改逻辑不同
     * 需要把ruleid带上去后台查询分配用户表
     */
    getList() {
      this.loading = true;
      if (this.form.id) {
        this.queryParam.ruleId = this.form.id;
      } else {
        this.queryParam.ruleId = "-1"; // 新增
      }
      findUserJoinRuleList(this.queryParam).then((response) => {
        this.form.ruleUsers = response.data.map((user) => ({
          ...user,
          // 将字符串 "1"/"0" 转换为布尔值
          isEnable: user.isEnable === "1", // "1" → true，其他值 → false
          maxCount: user.maxCount === null ? 20 : user.maxCount,
        }));

        this.loading = false;
      });
    },

    onClose() {
      this.open = false;
      this.reset();
      this.$emit("close");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$emit("close");
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        ruleName: undefined,

        ruleType: undefined,

        ruleCities: undefined,

        laiyuan: undefined,

        tags: undefined,

        status: "0",

        userId: undefined,

        ruleUsers: [],
      };
    },
    /** 新增按钮操作 */
    handleAdd(ruleType) {
      this.reset();
      this.form.ruleType = ruleType;
      this.form.ruleLogic = "1"; // 默认平均分配
      this.form.ruleSet = "2"; // 自定义分配
      /** 获取最大编号 */
      findMaxSort().then((response) => {
        this.form.sort = response.data;
        this.formTitle = "添加分配规则";
      });
      this.getList();
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.spinning = !this.spinning;
      const bizPushRuleId = row.id;
      getBizPushRule(bizPushRuleId).then((response) => {
        this.form = response.data;
        this.form.ruleUsers = this.form.ruleUsers.map((user) => ({
          ...user,
          // 将字符串 "1"/"0" 转换为布尔值
          isEnable: user.isEnable === "1", // "1" → true，其他值 → false
          maxCount: user.maxCount === null ? 20 : user.maxCount,
        }));

        this.form.laiyuan = JSON.parse(this.form.laiyuan);
        this.form.ruleCities = JSON.parse(this.form.ruleCities);

        this.formTitle = "修改分配规则";
        this.spinning = !this.spinning;
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const saveForm = JSON.parse(JSON.stringify(this.form));
          if (saveForm.laiyuan) {
            saveForm.laiyuan = JSON.stringify(saveForm.laiyuan);
          } else {
            saveForm.laiyuan = null;
          }
          if (saveForm.ruleCities) {
            saveForm.ruleCities = JSON.stringify(saveForm.ruleCities);
          } else {
            saveForm.ruleCities = null;
          }

          const queryParam = {
            id: saveForm.id,
            ruleType: saveForm.ruleType,
            ruleCities: saveForm.ruleCities,
            laiyuan: saveForm.laiyuan,
            ruleLogic: saveForm.ruleLogic,
          };

          //  判断规则是否已经存在
          findExistBizPushRule(queryParam).then((response) => {
            const existRule = response.data;
            if (existRule !== undefined && existRule !== null) {
              this.$message.error(
                existRule.ruleCities +
                  "-" +
                  existRule.laiyuan +
                  "对应的规则已存在[" +
                  existRule.ruleName +
                  "]",
                3
              );
            } else {
              if (saveForm.ruleUsers) {
                saveForm.ruleUsers = saveForm.ruleUsers.map((user) => ({
                  ...user,
                  // 布尔值 → 数字
                  isEnable: user.isEnable === true ? "1" : "0",
                }));
              }

              if (this.form.id !== undefined) {
                // 只保存启用或者修改的用户
                if (saveForm.ruleUsers) {
                  saveForm.ruleUsers = saveForm.ruleUsers.filter(
                    (item) => item.isEnable === "1" || item.id
                  );
                }
                updateBizPushRule(saveForm).then((response) => {
                  this.$message.success("修改成功", 3);
                  this.open = false;
                  this.$emit("ok");
                  this.$emit("close");
                });
              } else {
                // 过滤掉未启用的用户
                if (saveForm.ruleUsers) {
                  saveForm.ruleUsers = saveForm.ruleUsers.filter(
                    (item) => item.isEnable === "1"
                  );
                }
                addBizPushRule(saveForm).then((response) => {
                  this.$message.success("新增成功", 3);
                  this.open = false;
                  this.$emit("ok");
                  this.$emit("close");
                });
              }
            }
          });
        } else {
          return false;
        }
      });
    },
    back() {
      const index = "/biz/pushrule/index";
      this.$router.push(index);
    },
  },
};
